<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use App\Helpers\ValidatorResponse;
use App\Helpers\SuccessResponse;
use App\Http\Model\FaqCategory as Category;
use Illuminate\Support\Facades\DB;
use App\Http\Constant;

class FaqCategoryController extends Controller{

	public function __construct(){

	}

	public function listCategory(Request $request){
		$keywords = trim(strval($request->input('keywords')));
		$order_by = json_decode($request->input('order_by'), true);
		$structed = intval($request->input('structed')) == 1 ? 1 : 0;
		$order_by_arr = array();
		if(0 == count($order_by)){
			$order_by_arr = array('id desc');
		}else{
			foreach ($order_by as $key => $value) {
				if($value == 'asc' || $value == 'desc'){
					array_push($order_by_arr, $key.' '.$value);
				}else{
					continue;
				}
			}
		}
		$order_by_str = implode($order_by_arr, ',');
		$category_status = json_decode($request->input('category_status'), true);
		if(0 == count($category_status)){
			$category_status_arr = array(
				Constant::TFEX_FAQ_CATEGORY_STATUS_OPEN,
				Constant::TFEX_FAQ_CATEGORY_STATUS_CLOSE,
			);
		}else{
			$category_status_arr = array_values($category_status);
		}
			
		$data_sql = 'select * from faq_category where category_status in ('.implode($category_status_arr, ',').')';
		if(0 != strlen($keywords)){
			$data_sql .= ' and category_name like "%'.$keywords.'%"';
		}
		$data_sql .= ' order by '.$order_by_str;
		try{
			$category_data = DB::select($data_sql);
		}catch(\Exception $e){
			return SuccessResponse::handler('['.Constant::EC_SYSTEM_ERROR.'] An error accurred in system.');
		}
		$category_data = json_decode(json_encode($category_data), true);
		if(0 == count($category_data)){
			return SuccessResponse::handler('['.Constant::EC_NO_CATEGORY_MATCHED.'] No category found.');
		}else{
			if($structed){
				$category_data = $this->_getStructedCategoryData($category_data, 0);
			}
			$rtn_data = array(
				'where' => array(
					'keywords' => $keywords,
					'order_by' => $request->input('order_by'),
					'structed' => $structed,
					'category_status' => $category_status_arr,
				),
				'data' => $category_data,
			);
			return SuccessResponse::handler($rtn_data);
		}
	}

	private function _getStructedCategoryData($category_data, $parent_id){
		$sub_array = array();
		foreach ($category_data as $value) {
			if($value['parent_id'] == $parent_id){
				$sub_category_data = $this->_getStructedCategoryData($category_data, $value['id']);
				if(0 != count($sub_category_data)){
					$value['_sub'] = $sub_category_data;
				}
				array_push($sub_array, $value);
			}else{
				continue;
			}
		}
		return $sub_array;
	}

	public function add(Request $request){
		$validate = Validator::make($request->all(), [
			'parent_id' => 'required|integer|min:0',
			'category_name' => 'required|string',
			'category_status' => 'required|integer|min:1',
		]);
		if($validate->fails()){
			return ValidatorResponse::handler($validate->errors());
		}else{
			$category_model = new Category();
			$category_model->parent_id = $request->input('parent_id');
			$category_model->category_name = $request->input('category_name');
			$category_model->category_status = $request->input('category_status');
			try{
				$category_model->save();
			}catch(\Exception $e){	
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			$category_data = array(
				'id' => $category_model->id,
				'parent_id' => $category_model->parent_id,
				'category_name' => $category_model->category_name,
				'category_status' => $category_model->category_status,
			);
			return SuccessResponse::handler($category_data);
		}
	}

	public function edit(Request $request){
		$validate = Validator::make($request->all(), [
			'id' => 'required|integer|min:1',
			'parent_id' => 'required|integer|min:0',
			'category_name' => 'required|string',
			'category_status' => 'required|integer|min:1',
		]);
		if($validate->fails()){
			return ValidatorResponse::handler($validate->errors());
		}else{
			$category_model = new Category();
			$category_data = array(
				'parent_id' => $request->input('parent_id'),
				'category_name' => $request->input('category_name'),
				'category_status' => $request->input('category_status'),
			);
			try{
				$category_model->where('id', $request->input('id'))->update($category_data);
			}catch(\Exception $e){	
				return SuccessResponse::handler('['.$e->getCode().'] '.$e->getMessage());
			}
			$category_data['id'] = $request->input('id');
			return SuccessResponse::handler($category_data);
		}
	}

	public function detail($id){
		$validate = Validator::make(array('id' => $id), [
			'id' => 'required|integer|min:1',
		]);
		if($validate->fails()){
			return ValidatorResponse::handler($validate->errors());
		}else{
			$category_model = new Category();
			$category_data = $category_model->where('id', $id)->get()->toArray();
			if(0 == count($category_data)){
				return SuccessResponse::handler('No category [id='.$id.'] found.');
			}else{
				return SuccessResponse::handler($category_data);
			}
		}
	}

	public function delete(Request $request){
		$category_ids = json_decode($request->input('id'), true);
		if(0 == count($category_ids)){
			return SuccessResponse::handler('['.Constant::EC_NO_VALIDATE_CATEGORY_IDS.'] No validate category id or ids privided.');
		}else{
			$category_model = new Category();
			$update_data = array(
				'category_status' => Constant::TFEX_FAQ_CATEGORY_STATUS_DELETE,
			);
			try{
				$category_model->whereIn('id',  array_values($category_ids))->update($update_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.Constant::EC_SYSTEM_ERROR.'] An error accurred in system.');
			}
			return SuccessResponse::handler(array('id' => $category_ids));
		}
	}

	public function open(Request $request){
		$category_ids = json_decode($request->input('id'), true);
		if(0 == count($category_ids)){
			return SuccessResponse::handler('['.Constant::EC_NO_VALIDATE_CATEGORY_IDS.'] No validate category id or ids privided.');
		}else{
			$category_model = new Category();
			$update_data = array(
				'category_status' => Constant::TFEX_FAQ_CATEGORY_STATUS_OPEN,
			);
			try{
				$category_model->whereIn('id',  array_values($category_ids))->update($update_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.Constant::EC_SYSTEM_ERROR.'] An error accurred in system.');
			}
			return SuccessResponse::handler(array('id' => $category_ids));
		}
	}

	public function close(Request $request){
		$category_ids = json_decode($request->input('id'), true);
		if(0 == count($category_ids)){
			return SuccessResponse::handler('['.Constant::EC_NO_VALIDATE_CATEGORY_IDS.'] No validate category id or ids privided.');
		}else{
			$category_model = new Category();
			$update_data = array(
				'category_status' => Constant::TFEX_FAQ_CATEGORY_STATUS_CLOSE,
			);
			try{
				$category_model->whereIn('id',  array_values($category_ids))->update($update_data);
			}catch(\Exception $e){
				return SuccessResponse::handler('['.Constant::EC_SYSTEM_ERROR.'] An error accurred in system.');
			}
			return SuccessResponse::handler(array('id' => $category_ids));
		}
	}
}